package com.ikun.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikun.common.entity.*;
import com.ikun.search.dao.ElasticsearchDao;
import com.ikun.search.mapper.DockerMapper;
import com.ikun.search.service.CommentService;
import com.ikun.search.service.DockerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 医生表 服务实现类
 *
 * @author Guio
 * @since 2024-02-26
 */
@Slf4j
@Service
public class DockerServiceImpl extends ServiceImpl<DockerMapper, Docker> implements DockerService {

    public static final String INDEX_NAME = "docker";

    @Resource
    private DockerMapper dockerMapper;
    @Resource
    private ElasticsearchDao dao;
    @Resource
    private CommentService commentService;

    /**
     * 初始化医生索引
     */
    @Override
    public void initDockerIndex() {
        // 如果存在医生索引，先删除
        try {
            if (dao.existIndex(INDEX_NAME)) {
                dao.deleteIndex(INDEX_NAME);
            }
            // 再创建医生索引
            dao.createIndex(INDEX_NAME);
            //医生集合
            List<Docker> dockerList = dockerMapper.getAllDocker();
            if (dockerList != null) {
                //处理全部医生信息
                for (Docker docker : dockerList) {
                    handleDockerData(docker);
                }
                //将数据包包装到ES实体类中
                ArrayList<ElasticsearchEntity> entities = new ArrayList<>();
                dockerList.forEach(docker -> {
                    entities.add(new ElasticsearchEntity(String.valueOf(docker.getId()), docker));
                    log.info("docker:{}", docker);
                });
                //批量添加到ES中
                dao.insertBatch(INDEX_NAME, entities);
                log.info("docker集合:{},ES实体entities:{}", dockerList.size(), entities.size());
            } else {
                throw new RuntimeException("课程数据为空");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 搜索医生
     */
    @Override
    public PageEntity<Docker> searchDocker(Map<String, String> map) {
        int current = 1;    //当前页
        int form = 0;       //当前页起始索引
        int size = 10;      //每页条数
        Map<String, String> search = new HashMap<>();
        Map<String, String> sort = new HashMap<>();
        if (map.containsKey("current")) {
            current = Integer.parseInt(map.get("current"));
            form = (current - 1) * size;
        }
        if (map.containsKey("size")) {
            size = Integer.parseInt(map.get("size"));
        }
        if (map.containsKey("search")) {
            search = JSON.parseObject(map.get("search"), Map.class);
        }
        if (map.containsKey("sort")) {
            sort = JSON.parseObject(map.get("sort"), Map.class);
            if (sort.get("field").isEmpty() || sort.get("type").isEmpty()) {
                sort = null;
            }
        }
        try {
            PageEntity<Docker> pageEntity = dao.searchPageByMap(INDEX_NAME, search, sort, form, size, Docker.class,
                    "name");
            pageEntity.setCurrent(current);
            return pageEntity;
        } catch (IOException e) {
            log.error("搜索出错", e);
            return new PageEntity<>();
        }
    }

    /**
     * 用医生id查医生信息
     */
    @Override
    public Docker getDockerById(Integer id) {
        Docker docker = dockerMapper.getDockerById(id);
        handleDockerData(docker);
        return docker;
    }

    /**
     * 处理医生信息
     */
    private void handleDockerData(Docker docker) {
        //遍历医生擅长疾病集合：计算各疾病索引，添加到医生擅长
        StringBuilder proficientIn = new StringBuilder();
        List<Disease> diseaseList = docker.getDiseaseList();
        int size = diseaseList.size();
        for (int i = 0; i < size; i++) {
            //疾病索引
            Disease disease = diseaseList.get(i);
            disease.setDIndex(disease.getDName().charAt(0));
            //拼接擅长疾病字符串
            proficientIn.append(disease.getDName());
            if (i != size - 1) {
                proficientIn.append(",");
            }
        }
        docker.setProficientIn(proficientIn.toString());
        //计算评分
        List<Comment> commentList = commentService.getScoreByDockerId(docker.getId());
        if (!commentList.isEmpty()) {
            Double totalScore = 0.0; //总评分
            for (Comment comment : commentList) {
                Integer score = comment.getScore();
                totalScore += score;
            }
            double endScore = totalScore / commentList.size();
            // 使用 DecimalFormat 格式化评分，保留一位小数
            DecimalFormat df = new DecimalFormat("#.#");
            String formattedScore = df.format(endScore);
            // 将格式化后的评分转换为 double 类型并设置给 Docker 对象
            docker.setScore(Double.parseDouble(formattedScore));
        } else {
            docker.setScore(-1.0);
        }
    }

}
